var Q = require('q'),
    _ = require('lodash'),
    WorkLoaction = require('./WorkLocation.server.controller.js'),
    StationWork = require('../../../Initialize/server/controllers/StationWork.server.controller.js'),
    entityCollection = require('../../../Base/server/controllers/EntityCollection'),
    routingController = require('./Routing.server.controller');

//根据根据工艺路线查找全部工序
exports.findOperations = function (routingId, completeFun) {
    var entity = entityCollection.getEntity("Operation");
    entity.find({Routing: routingId}, {Sequence: 1}, {path: 'Work'}, function (err, records) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询错误';
            newErr.message = '查询工序错误，请检查查询参数！';
            completeFun(newErr);
        }
        else {
            completeFun(null, records);
        }
    });
};

//根据工艺路线查找全部质检序
exports.findQCOperations = function (routingId, completeFun) {
    this.findOperations(routingId, function (err, records) {
        if (err) {
            completeFun(err);
        }
        else {
            var qcOpperations = [];
            for (var i = 0; i < records.length; i++) {
                if (records[i].IsQCpoint) {
                    qcOpperations.push(records[i]);
                }
                ;
            }
            completeFun(null, qcOpperations);
        }
    });
};

//根据工艺路线ID和作业ID查找工序
exports.findByRoutingAndWork = function (routingId, workId, completeFun) {
    var entity = entityCollection.getEntity("Operation");
    entity.findOne({Routing: routingId, Work: workId}, {path: 'Work'}, function (err, record) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询工序错误';
            newErr.message = '根据工艺路线和作业，没有找到对应的工序！';
            completeFun(newErr);
        }
        else {
            completeFun(null, record);
        }
    });
};

//根据物料和作业查找工序
exports.findByItemMasterAndWork = function (itemMasterId, workId, completeFun) {
    var self = this;
    routingController.findByItemMaster(itemMasterId, function (err, routingRecord) {
        if (err) {
            completeFun(err);
        }
        else {
            if (routingRecord == null) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '查询工艺路线失败';
                newErr.message = '该物料没有对应的工艺路线！';
                completeFun(newErr);
            }
            else {
                self.findByRoutingAndWork(routingRecord._id, workId, function (err, operationRecord) {
                    completeFun(err, operationRecord);
                });
            }
        }
    });
};

//根据物料和作业集合查找工序集合
exports.findByRoutingAndWorks = function (routingId, workIds) {
    var entity = entityCollection.getEntity("Operation");
    return new Promise(function(resolve, reject) {
        entity.find({Routing: routingId, Work: {$in: workIds}}, {Sequence: 1}, {path: 'Work'}, function (err, records) {
            if (err) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '查询工序错误';
                newErr.message = '根据工艺路线和作业，没有找到对应的工序！';
                reject(newErr);
            }
            else {
                resolve(records);
            }
        });
    });
};

//根据物料和作业集合查找对应的工序集合
exports.findByItemMasterAndWorks = function (itemMasterId, workIds) {
    var self = this;
    return new Promise(function(resolve, reject) {
        routingController.findByItemMaster(itemMasterId, function (err, routingRecord) {
            if (err) {
                reject(err);
            }
            else {
                if (routingRecord == null) {
                    var newErr = new Error();
                    newErr.leval = 9;
                    newErr.title = '查询工艺路线失败';
                    newErr.message = '该物料没有对应的工艺路线！';
                    reject(newErr);
                }
                else {
                    self.findByRoutingAndWorks(routingRecord._id, workIds).then(operations => resolve(operations)).catch(err => reject(err));
                }
            }
        });
    });
};

//查找部门对应物料的所有工序
exports.findByDepartmentAndItem = function(departmentId, itemId) {
    var self = this;
    return new Promise(function(resolve, reject) {
        //1.查部门所有工位
        WorkLoaction.findByDepartment(departmentId, function(err, workLoactions){
            if(err){
                reject(err);
            }
            else{
                if(workLoactions.length > 0){
                    var workLoactionIds = [];
                    workLoactions.forEach(function(wlRecord){
                        workLoactionIds.push(wlRecord._id);
                    });
                    //2.根据工位查找对应的工位作业交叉表，从而找到工位对应的所有作业
                    StationWork.findByWorkLocationIds(workLoactionIds).then(function(stationWorks){
                        var workIds = [];
                        stationWorks.forEach(function(stationWork){
                            workIds.push(stationWork.Work._id);
                        });

                        //3.根据作业和物料找到所有工序
                        return self.findByItemMasterAndWorks(itemId, workIds);
                    }).then(operations => resolve(operations)).catch(err => reject(err));
                }
            }
        });
    });
};

//根据物料和作业查找工序
exports.findCPByItemMasterAndWork = function (itemMasterId, workId, completeFun) {
    routingController.findByItemMaster(itemMasterId, function (err, routingRecord) {
        if (err) {
            completeFun(err);
            return;
        }
        if (routingRecord == null) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询工艺路线失败';
            newErr.message = '该物料没有对应的工艺路线！';
            completeFun(newErr);
            return;
        }
        var entity = entityCollection.getEntity("Operation");
        entity.findOne({Routing: routingRecord._id, Work: workId, IsCountPoint: true}, null, function (err, record) {
            if (err) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '查询工序错误';
                newErr.message = '根据工艺路线和作业，没有找到对应的工序！';
                completeFun(newErr);
            } else {
                completeFun(null, record);
            }
        });
    });
};

//根据工艺路线ID和作业ID查找工序
exports.findByRoutingAndWork2 = function (routingId, workId, completeFun) {
    var entity = entityCollection.getEntity("Operation");
    entity.findOne({Routing: routingId, Work: workId}, [{path: 'Name'}, {path: '_id'}], function (err, record) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询工序错误';
            newErr.message = '根据工艺路线和作业，没有找到对应的工序！';
            completeFun(newErr);
        }
        else {
            completeFun(null, record);
        }
    });
};

//根据物料和作业查找工序
exports.findByItemMasterAndWork2 = function (itemMasterId, workId, completeFun) {
    var self = this;
    routingController.findByItemMaster(itemMasterId, function (err, routingRecord) {
        if (err) {
            completeFun(err);
        }
        else {
            if (routingRecord == null) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '查询工艺路线失败';
                newErr.message = '该物料没有对应的工艺路线！';
                completeFun(newErr);
            }
            else {
                self.findByRoutingAndWork2(routingRecord._id, workId, function (err, operationRecord) {
                    completeFun(err, operationRecord);
                });
            }
        }
    });
};

//根据当前工序序号查找下一工序
exports.findNextSequence = function (routingId, sequence) {
    var deferred = Q.defer();

    sequence = sequence ? sequence : -1;// 此时返回的是第一个工序序号

    var entity = entityCollection.getEntity("Operation");
    entity.Entity
        .find(
            {Routing: routingId, Sequence: {$gt: sequence}}
        ).sort({Sequence: 1})
        .limit(1)
        .exec(function (err, records) {
            if (err) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '查询工序序号错误';
                newErr.message = '查询工序序号错误，请检查查询参数！';
                deferred.reject(newErr);
                return;
            }
            if (!records || records.length === 0) {
                deferred.resolve();
                return;
            }
            deferred.resolve(records[0]);
        });

    return deferred.promise;
};

//根据当前工序查找下一质检工序
exports.findNextOperation = function (routingId, sequence) {
    var deferred = Q.defer();
    sequence = sequence ? sequence : -1;
    var entity = entityCollection.getEntity("Operation");
    entity.find({
        Routing: routingId,
        Sequence: {$gt: sequence},
        IsQCpoint: true
    }, {Sequence: 1}, [{
        path: "Work",
        select: "Code Name"
    }], function (err, operationRecords) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询工序错误';
            newErr.message = '查询工序错误，请检查查询参数！';
            deferred.reject(newErr);
        } else {
            if (!operationRecords || operationRecords.length === 0) {
                deferred.resolve();
                return;
            }
            deferred.resolve(operationRecords[0]);
        }
    });
    return deferred.promise;
};

// 根据当前工序序号和下一工序序号查找遗漏检查点工序
exports.findMissingOperation = function (routingId, currentSequence, nextSequence, projection, populate) {
    var deferred = Q.defer();

    if (currentSequence <= nextSequence) {
        deferred.resolve();
    } else {
        projection = projection ? projection : {};
        var entity = entityCollection.getEntity("Operation"),
            result = entity.Entity.find({
                Routing: routingId,
                Sequence: {$gt: nextSequence, $lt: currentSequence},
                IsCheckPoint: true
            }, projection);
        if (populate) {
            result = result.populate(populate);
        }

        result.then(function (records) {
            deferred.resolve(records);
        }, function () {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询遗漏检查点工序错误';
            newErr.message = '查询失败，请检查查询参数！';
            deferred.reject(newErr);
        });
    }

    return deferred.promise;
};

exports.findCountPoint = function (completeFun) {
    var entity = entityCollection.getEntity("Operation");
    entity.find({IsCountPoint: true}, null, null, function (err, records) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询错误';
            newErr.message = '查询工序错误，请检查查询参数！';
            completeFun(newErr);
        } else {
            var countPoints = [];
            _.forEach(records, function (record) {
                countPoints.push(record._id);
            });
            if (countPoints.length === 0) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '查询错误';
                newErr.message = '工序没有统计点,无法统计完工数量！';
                completeFun(newErr);
            } else {
                completeFun(null, countPoints);
            }

        }
    });
};
